package com.cjh.admin.controller;

import com.alibaba.fastjson.JSON;
import com.cjh.admin.config.TokenThreadLocal;
import com.cjh.common.dto.AddCommodityDTO;
import com.cjh.common.dto.CommodityPagingDTO;
import com.cjh.common.dto.UpdateCommodityDTO;
import com.cjh.common.response.Result;
import com.cjh.common.service.CommodityService;
import com.cjh.common.service.UploadService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cjh
 * @since 2022-01-19
 */
@RestController
@RequestMapping("/commodity")
public class CommodityController {
    @Autowired
    CommodityService commodityService;
    @Autowired
    UploadService uploadService;
    @ApiOperation("获取商品进行分页")
    @GetMapping("/getPagingCommodity")
    public Result getPagingCommodity(@RequestParam String commodityPagingDTO){
        CommodityPagingDTO commodityPagingDTO1 = JSON.parseObject(commodityPagingDTO, CommodityPagingDTO.class);
        commodityPagingDTO1.setUsername(TokenThreadLocal.get());
        return commodityService.getPagingCommodity(commodityPagingDTO1);
    }

    @ApiOperation("根据id获取商品")
    @GetMapping("/getCommodityById")
    public Result getCommodityById(@RequestParam Integer id){
        return commodityService.getCommodityById(id);
    }

    @ApiOperation("上传商品图片")
    @PostMapping("/upload")
    public Result upload(@RequestBody MultipartFile file){
        String s = uploadService.uploadFile(file, "commodity/");
        return new Result().setCode(200).setMessage("操作成功！").setData(s);
    }

    @ApiOperation("增加商品信息")
    @PostMapping("/addCommodity")
    public Result addCommodity(@RequestBody AddCommodityDTO addCommodityDTO){
        return commodityService.addCommodity(addCommodityDTO);
    }

    @ApiOperation("修改商品信息")
    @PostMapping("/updateCommodity")
    public Result updateCommodity(@RequestBody UpdateCommodityDTO updateCommodityDTO){
        return commodityService.updateCommodity(updateCommodityDTO);
    }

    @ApiOperation("删除商品")
    @PostMapping("/deleteCommodity")
    public Result deleteCommodity(@RequestBody Map<String,Integer> map){
        return commodityService.deleteCommodity(map.get("commodity"));
    }
}
